package com.molichuxing.services.infrastructure.service.impl;

import com.alibaba.fastjson.JSON;
import com.molichuxing.services.infrastructure.bean.GoodsSpecBean;
import com.molichuxing.services.infrastructure.convertor.Convert;
import com.molichuxing.services.infrastructure.dao.GoodsSpecMapper;
import com.molichuxing.services.infrastructure.dto.request.create.GoodsSpecCreateDto;
import com.molichuxing.services.infrastructure.dto.response.GoodsSpecDto;
import com.molichuxing.services.infrastructure.service.GoodsSpecService;
import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品规格表 服务实现类
 * </p>
 *
 * @author xuelin yi
 * @since 2019-08-12
 */
@Service("goodsProductSpecService")
public class GoodsSpecServiceImpl implements GoodsSpecService {

    private static final Logger log = Logger.getLogger(GoodsSpecServiceImpl.class);

    @Resource
    private GoodsSpecMapper goodsSpecMapper;

    @Override
    public Map<Integer, List<GoodsSpecDto>> getGoodsProductSpecList(List<Integer>  goodsIdList, List<Integer>  specIds) {
        log.info("根据商品id集合查询商品的规格信息。 goodsId ： "+ JSON.toJSONString(goodsIdList));
        List<GoodsSpecBean> list = goodsSpecMapper.getGoodsProductSpecList(goodsIdList, specIds);
        if(null == list) {
            return null;
        }
        return Convert.toGoodsProductSpecBeanDto(list).stream().collect(Collectors.groupingBy(GoodsSpecDto::getGoodsId));
    }

    @Override
    public List<GoodsSpecDto> getGoodsProductSpecList(Integer goodsId, List<Integer>  specId) {
        log.info("根据商品id查询商品的规格信息。 goodsId ： "+ JSON.toJSONString(goodsId));
        List<GoodsSpecBean> list = goodsSpecMapper.getGoodsProductSpecList(Arrays.asList(goodsId), specId);
        return Convert.toGoodsProductSpecBeanDto(list);
    }

    @Override
    public int createGoodsProductSpec(List<GoodsSpecCreateDto> goodsSpecList) {
        log.info("插入商品和规格的关联关系信息 goodsSpecList :"+JSON.toJSONString(goodsSpecList));
        for(GoodsSpecCreateDto goodsSpecCreateDto : goodsSpecList) {
            GoodsSpecBean goodsSpecBean = new GoodsSpecBean();
            BeanUtils.copyProperties(goodsSpecCreateDto, goodsSpecBean);
            log.info("插入商品和规格的关联关系信息 入参 goodsSpecBean :"+JSON.toJSONString(goodsSpecBean));
            int result = goodsSpecMapper.create(goodsSpecBean);
            log.info("插入商品和规格的关联关系信息 出参 result :"+JSON.toJSONString(result));
        }
        return 1;
    }
}
